<template>
  <a-modal
    title="选择成员"
    :visible="modalState"
    width="760px"
    :mask-closable="false"
    :destroy-on-close="true"
    :z-index="1001"
    @ok="handleOk(false)"
    @cancel="handleCancel(false)"
  >
    <div class="power-manage">
      <div class="left">
        <span class="font-color">选择</span>
        <div class="public" style="height: 514px">
          <div class="white-bg search">
            <a-input
              v-model:value="userName"
              autocomplete="off"
              placeholder="请输入成员姓名搜索"
              @change="onSearch()"
              @keyup.enter="onSearch()"
            >
              <template #prefix
                ><img src="@/assets/images/accommodation/jiaoxue_icon_sousuo.png"
              /></template>
            </a-input>
          </div>
          <!-- <p>当前选中条数：{{ list.length }}/总选中条数：{{ selectTotal.length }}</p>
          <p>当多选选择数量：{{ selectStudentValue.length }}</p>

          已选人数：{{ selectTotal.length }}/剩余可选人数：{{ 10 - selectTotal.length }}/总人数：{{
            userAmount
          }}
          总人数：{{ isUserAll.length }} -->
          <div v-if="!isSearch" class="nav">
            <a-breadcrumb style="white-space: nowrap">
              <a-breadcrumb-item><a @click="depList(0, 0)">通讯录</a></a-breadcrumb-item>
              <template v-for="(item, index) of deptName" :key="index">
                <a-breadcrumb-separator>></a-breadcrumb-separator>
                <a-breadcrumb-item>
                  <a @click="depList(item, index + 1)">{{ item.deptName }}</a>
                </a-breadcrumb-item>
              </template>
            </a-breadcrumb>
          </div>
          <div class="white-bg select-all" style="height: 396px">
            <div style="width: 310px; height: 380px; overflow: auto; padding-left: 0px">
              <!-- <a-checkbox
                v-show="!isSearch"
                v-model:checked="selectedCheckedAll"
                style="color: #999999"
                @change="onCheckAllChange"
              >
                全选
              </a-checkbox> -->
              <a-checkbox-group v-model:value="selectStudentValue">
                <a-menu
                  v-model:openKeys="openStudentValue"
                  v-model:selectedKeys="selectStudentValue"
                  style="width: 256px; padding-left: 0px; user-select: none"
                  mode="inline"
                  :selectable="false"
                >
                  <a-sub-menu
                    v-for="item of deptStructure.children"
                    :key="item.id"
                    @click="onDeptName(item)"
                  >
                    <template #expandIcon>
                      <!-- <down-outlined /> -->
                      <right-outlined />
                    </template>
                    <template v-slot:title>
                      <!-- <a-checkbox :value="item.id" @click.stop="onDeptNameChecked($event, item)" /> -->
                      <span style="margin-left: 10px"> {{ item.deptName }} </span>
                    </template>
                  </a-sub-menu>

                  <a-menu-item v-for="item of deptStructure.deptPersonChildren" :key="item.userId">
                    <a-checkbox :value="item.userId" @click="onRealNameChecked($event, item)">
                      <!-- <a-radio
                      value="item.userId"
                      @click="onRealNameChecked($event, item)"
                    > -->

                      <img
                        v-if="item.avatar && item.avatar !== null && item.avatar !== undefined"
                        :src="item.avatar"
                        style="
                          width: 20px;
                          height: 20px;
                          border-radius: 50px;
                          margin-right: 10px;
                          display: inline-block;
                        "
                      />
                      <img
                        v-else
                        src="@/assets/images/accommodation/icon_mrtx.png"
                        alt=""
                        style="
                          width: 20px;
                          height: 20px;
                          border-radius: 50px;
                          margin-right: 10px;
                          display: inline-block;
                        "
                      />
                      <span style="font-size: 14px; margin-right: 10px; color: #000000">
                        {{ item.realName }}
                      </span>
                      <span v-if="isSearch" style="font-size: 12px; color: #000000">
                        {{ item.deptName }}
                      </span>
                      <!-- </a-radio> -->
                    </a-checkbox>
                  </a-menu-item>
                </a-menu>
              </a-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <span class="font-color">已选</span>
        <div class="public">
          <div style="background: #ffffff; padding: 20px; height: 480px; overflow: auto">
            <div v-for="elem in selectTotal" :key="elem.userId">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 10px 0;
                  border-bottom: 1px solid rgb(226, 226, 226);
                "
              >
                <div style="display: flex; align-items: center">
                  <img
                    v-if="elem.avatar && elem.avatar !== null && elem.avatar !== undefined"
                    :src="elem.avatar"
                    style="width: 20px; height: 20px; border-radius: 50px; margin-right: 10px"
                  />
                  <img
                    v-else
                    src="@/assets/images/accommodation/icon_mrtx.png"
                    alt=""
                    style="width: 20px; height: 20px; border-radius: 50px; margin-right: 10px"
                  />
                  <span style="font-size: 14px; font-weight: 400; color: #000000">{{
                    elem.realName
                  }}</span>
                </div>
                <CloseCircleOutlined @click="onCancel(elem)" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script>
import { computed, defineComponent, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { CloseCircleOutlined, DownOutlined, RightOutlined } from '@ant-design/icons-vue';
import { getUserList, getAllDeptInfo } from '@/api/dormitoryManage';
import SidebarItem from './sidebarItem';

export default defineComponent({
  /** ****************引用的数据***********************/
  components: {
    CloseCircleOutlined,
    DownOutlined,
    RightOutlined
  },
  props: {
    modalState: Boolean, // 弹窗状态
    deptUserList1: Array, // 部门数据
    userList1: Array, // 成员数据

    /** ************************* 测试开始 ****************************************** */
    deptStructure: Object, // 部门结构数据
    selectUserList: Array, // 人员回显
    userAmount: Number, // 部门结构数据
    deptName: Array, // 部门面包屑
    isUserAll: Array, // 全部成员
    deptStructureCopy: Object // 部门结构数据备份
    /** ************************* 测试结束 ***************************************** */
  },
  emits: {
    handleCancel: null, // 取消事件
    handleOk: null, // 确定事件

    /** ************************* 测试开始 ****************************************** */
    deplist: null,
    deptBreadcrumb: null
    /** ************************* 测试结束 ***************************************** */
  },
  setup(props, context) {
    /** ****************数据区域***********************/
    const openStudentValue = ref([]);
    const selectStudentValue = ref([]);

    const selectTotal = ref([]);
    /** ****************方法区域***********************/
    // const deptName = ref([]); // 部门面包屑标题
    const list = ref([]); // 当前部门选择人员
    const listAll = ref([]); // 当前部门全部人员
    const selectedCheckedAll = ref(false); // 是否全选
    const userListAll = ref([]); // 当前部门下所有成员
    const userName = ref(undefined); // 成员搜索
    const isSearch = ref(false); // 是否搜索
    // const userAmount = ref(0); // 当前部门总人数

    // 成员搜索
    const onSearch = () => {
      if (userName.value) {
        isSearch.value = true;
        let list = [];
        console.log(props.isUserAll);
        console.log(props.deptStructureCopy);
        props.isUserAll.forEach(elem => {
          let arr = elem.realName.match(userName.value);
          if (arr !== null) {
            props.deptStructureCopy.deptPersonChildren.forEach(v => {
              if (v.userId === elem.userId) elem.deptName = v.deptName;
            });
            if (props.deptStructureCopy.children) {
              getUserDept(props.deptStructureCopy.children, elem);
            }
            // getUserDept(props.deptStructureCopy, elem);
            list.push(elem);
          }
        });
        console.log(list);
        console.log(props.deptStructureCopy);
        list = deduplication(list);
        context.emit('deptListAll', {
          children: [],
          deptPersonChildren: list
        });
      } else {
        isSearch.value = false;
        context.emit('deptBreadcrumb', 0);
        context.emit('deptListAll', props.deptStructureCopy);
      }
    };
    // 查找该人员所在部门
    const getUserDept = (dept, user, deptName) => {
      console.log(dept);
      dept.forEach(v => {
        v.deptPersonChildren.forEach(x => {
          x.deptName = deptName ? `${deptName}-${v.deptName}` : v.deptName;
          console.log(x.userId, user.userId, x.deptName, x.realName);
          if (x.userId === user.userId) user.deptName = x.deptName;
        });
        if (v.children) {
          let name = deptName ? `${deptName}-${v.deptName}` : v.deptName;
          getUserDept(v.children, user, name);
        }
      });
    };
    // 保留数组对象中非重复数据
    const deduplication = arr => {
      let idList = [...new Set(arr.map(x => x.userId))];
      let arrList = [];
      idList.forEach(elem => {
        arrList.push(arr.find(x => x.userId === elem));
      });
      return arrList;
    };

    // 是否禁用多选
    const isDisabled = computed(() => {
      let boolean = false;
      selectTotal.value.forEach(elem => {
        if (
          selectTotal.value.length >= 10 &&
          selectStudentValue.value.indexOf(elem.userId) === -1
        ) {
          boolean = true;
        } else {
          boolean = false;
        }
      });
      return boolean;
    });
    // 点击部门
    function onDeptName(item) {
      context.emit('deplist', item);
    }
    const deptStructureComputed = computed(() => props.deptStructure);
    watch(deptStructureComputed, data => {
      console.log('监听部门改变=======>', data);
      isDeptShow();
      console.log(userListAll.value);
    });
    // 回显 length
    const isDeptShow = () => {
      console.log('回显', props);
      list.value = [];
      selectStudentValue.value = [];
      userListAll.value = [];
      let arr = selectTotal.value.map(x => x.userId);
      console.log(arr);
      props.deptStructure.deptPersonChildren.forEach(k => {
        if (arr.indexOf(k.userId) !== -1) {
          list.value.push(k);
          selectStudentValue.value.push(k.userId);
        }
      });
      if (props.deptStructure.children) {
        if (props.deptStructure.children.length) {
          props.deptStructure.children.forEach((elem, index) => {
            elem.deptPersonChildren.forEach(x => {
              if (arr.indexOf(x.userId) !== -1) {
                list.value.push(x);
                selectStudentValue.value.push(elem.id);
              }
            });
            if (elem.children) {
              if (elem.children.length) {
                isDeptUser(elem.children, elem, arr);
              }
            }
          });
        }
      }

      selectStudentValue.value = [...new Set(selectStudentValue.value)];
    };
    // 递归回显
    const isDeptUser = (data, elem, arr) => {
      data.forEach(v => {
        v.deptPersonChildren.forEach(x => {
          if (arr.indexOf(x.userId) !== -1) {
            list.value.push(x);
            selectStudentValue.value.push(elem.id);
          }
        });
        console.log('沙和尚', v);
        if (v.children) {
          if (v.children.length) {
            isDeptUser(v.children, elem, arr);
          }
        }
      });
    };

    // 已选中的人 length
    const onRealNameChecked = (e, userList) => {
      console.log('成员单选========>e', e);
      console.log('成员单选========>userList', userList);
      console.log('list:', list);
      list.value = [];
      selectTotal.value = [];
      if (e.target.checked) {
        // message.error('只能选择一位教职工');
        isDeptShow();
        list.value.push(userList);
        selectTotal.value.push(userList);
      } else {
        list.value = list.value.filter(elem => elem.userId !== userList.userId);
        selectTotal.value = selectTotal.value.filter(elem => elem.userId !== userList.userId);
      }
      console.log(selectStudentValue.value);
      console.log('循环选择数组是什么', props.deptStructure.deptPersonChildren);
    };
    // 全选标识
    const listLength = computed(() => list.value.length);
    watch(listLength, () => {
      if (!listLength.value) {
        selectedCheckedAll.value = false;
      } else {
        selectedCheckedAll.value = true;
      }
    });
    // 全选循环搜索成员执行方法
    const implementCheckedAll = () => {
      props.deptStructure.deptPersonChildren.forEach(elem => {
        let arr = selectTotal.value.map(x => x.userId);
        if (arr.indexOf(elem.userId) === -1 && selectTotal.value.length < 10) {
          list.value.push(elem);
          selectTotal.value.push(elem);
          selectStudentValue.value.push(elem.userId);
        }
      });
      if (props.deptStructure.children.length) {
        let selectTotalList = [];
        props.deptStructure.children.forEach(elem => {
          selectTotalList = selectTotal.value.map(x => x.userId);
          elem.deptPersonChildren.forEach(x => {
            if (selectTotalList.indexOf(x.userId) === -1 && selectTotal.value.length < 10) {
              list.value.push(x);
              selectTotal.value.push(x);
              selectStudentValue.value.push(elem.id);
            }
          });
          if (elem.children) {
            if (elem.children.length) {
              isDeptCheckedAll(elem.children, elem, selectTotalList);
            }
          }
        });
      }
      selectStudentValue.value = [...new Set(selectStudentValue.value)];
    };
    // 勾选部门
    const onDeptNameChecked = (e, data) => {
      userListAll.value = [];
      userListAll.value = [...userListAll.value, ...data.deptPersonChildren];
      getDeptListArr(data.children);
      if (e.target.checked) {
        console.log('勾选');
        userListAll.value.forEach(elem => {
          if (selectTotal.value.length) {
            let arr = selectTotal.value.map(x => x.userId);
            if (arr.indexOf(elem.userId) === -1 && selectTotal.value.length < 10) {
              list.value.push(elem);
              selectTotal.value.push(elem);
            }
          } else {
            if (selectTotal.value.length < 10) {
              list.value.push(elem);
              selectTotal.value.push(elem);
            }
          }
        });
      } else {
        console.log('取消勾选');
        let arr = userListAll.value.map(x => x.userId);
        let selectTotalCopy = [];
        let listCopy = [];
        selectTotal.value.forEach(elem => {
          if (arr.indexOf(elem.userId) === -1) selectTotalCopy.push(elem);
        });
        list.value.forEach(elem => {
          if (arr.indexOf(elem.userId) === -1) listCopy.push(elem);
        });
        selectTotal.value = selectTotalCopy;
        list.value = listCopy;
      }
    };
    // 递归获取当前部门下所有成员
    const getDeptListArr = data => {
      data.forEach(k => {
        userListAll.value = [...userListAll.value, ...k.deptPersonChildren];
        if (k.children.length) {
          getDeptListArr(k.children);
        }
      });
    };
    // 全选
    const onCheckAllChange = e => {
      userListAll.value = [];
      if (e.target.checked) {
        implementCheckedAll();
      } else {
        if (selectTotal.value.length < 10 && list.value.length < props.userAmount) {
          console.log('全选');
          selectedCheckedAll.value = true;
          // 全选
          implementCheckedAll();
          return false;
        }
        // 非全选
        let selectId = list.value.map(x => x.userId); // 当前部门选中人员ID
        let unSelectId = []; // 剩余全部选中人员
        selectTotal.value.forEach(elem => {
          if (selectId.indexOf(elem.userId) === -1) {
            unSelectId.push(elem);
          }
        });
        selectTotal.value = unSelectId;
        list.value = [];
        selectStudentValue.value = [];
      }
    };
    // 部门全选
    const isDeptCheckedAll = (data, elem, arr) => {
      data.forEach(v => {
        arr = selectTotal.value.map(x => x.userId);
        v.deptPersonChildren.forEach(x => {
          if (arr.indexOf(x.userId) === -1 && selectTotal.value.length < 10) {
            list.value.push(x);
            selectTotal.value.push(x);
            selectStudentValue.value.push(elem.id);
          }
        });
        if (v.children.length) {
          isDeptCheckedAll(v.children, elem, arr);
        }
      });
    };
    // 点击标题
    const depList = (data, index) => {
      isSearch.value = false;
      selectedCheckedAll.value = false;
      userName.value = undefined;
      if (data === 0) {
        context.emit('deptListAll', props.deptStructureCopy);
      } else {
        context.emit('deplist', data);
      }
      context.emit('deptBreadcrumb', index);
    };
    // 清除
    const onCancel = item => {
      selectTotal.value.splice(selectTotal.value.indexOf(item), 1);
      isDeptShow();
    };
    /** ************************* 测试结束 ****************************************** */

    // 取消
    function handleCancel(state) {
      resetForm();
      context.emit('handleCancel', state);
    }
    // 确定
    function handleOk() {
      userName.value = undefined;
      context.emit('handleOk', selectTotal.value);
    }
    // 重置信息
    const resetForm = () => {
      list.value = [];
      selectTotal.value = [];
      selectStudentValue.value = [];
      isSearch.value = false;
      userName.value = undefined;
      context.emit('deptBreadcrumb', 0);
    };
    /** ****************必须抛出***********************/
    return {
      openStudentValue,
      selectStudentValue,
      handleCancel,
      handleOk,
      list,
      userName,
      onCancel,
      onDeptName,
      depList,
      onRealNameChecked,
      onDeptNameChecked,
      onCheckAllChange,
      onSearch,
      deduplication,
      isSearch,

      selectTotal,
      listAll,
      selectedCheckedAll,
      isDisabled
    };
  }
});
</script>

<style lang="less" scoped>
.power-manage {
  display: flex;
  .font-color {
    color: #666666;
  }
  .public {
    background: #f8f8f8;
    padding: 16px 10px;
    margin: 13px 0px 16px;
  }
  .white-bg {
    background: #ffffff;
    border-radius: 5px;
    margin-bottom: 14px;
  }
  .left {
    width: 311px;
    .nav {
      height: 32px;
      line-height: 32px;
      overflow-x: auto;
    }
    .search {
      height: 40px;
      line-height: 40px;
      // padding: 9px 100.5px 9px 15px;
    }
    .select-all {
      padding: 13px 18px;
      .checkbox {
        display: flex;
        margin-top: 16px;
      }
    }
  }
  .right {
    flex: 1;
    margin-left: 16px;
    .u-felx {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 14px;
    }
    /deep/.ant-collapse {
      background-color: #ffffff !important;
    }
    .class-title {
      margin-bottom: 19.5px;
      display: flex;
      justify-content: space-between !important;
    }
    .right {
      color: #999999;
      display: flex;
      justify-content: space-between;
      align-items: center;
      img {
        margin-left: 31px;
      }
    }
    .content {
      display: flex;
      flex-wrap: wrap;
      .data-btn {
        color: @color-test;
        width: 76px;
        text-align: center;
        line-height: 28px;
        height: 28px;
        background: rgba(253, 244, 236, 0.5);
        border-radius: 5px;
        margin-bottom: 5px;
        margin-right: 16px;
      }
    }
    .content-device {
      display: flex;
      flex-wrap: wrap;
      padding-left: 1px !important;
      .check-box {
        margin-bottom: 5px;
        margin-left: -1px !important;
        color: #999999;
      }
    }
  }
  .left-device {
    width: 536px;
    .checkbox-device {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      /deep/ .ant-checkbox + span {
        display: flex !important;
        height: 56px;
        align-items: center;
      }
      .checkbox-spacing {
        width: 120px;
        margin-left: 8px;
        margin-right: 50px;
      }
      .name {
        width: 161px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .titlee {
        width: 200px;
        margin: 0 38px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
      }
    }
    /deep/.ant-collapse-item:last-child > .ant-collapse-content {
      overflow: hidden !important;
    }
  }
  .right-device {
    flex: 1;
    margin-left: 16px;
  }
  /deep/.micro-ant-collapse {
    border: none;
  }
  /deep/.micro-ant-collapse-item {
    border-bottom: none;
  }
}
/deep/.micro-dormitory-menu-submenu-title {
  padding-left: 0 !important;
}
/deep/.micro-dormitory-menu-item {
  padding-left: 0 !important;
}
/deep/.micro-dormitory-menu-inline {
  border: 0;
}
/deep/.micro-dormitory-menu-inline .micro-dormitory-menu-item::after {
  border: 0;
}
/deep/.micro-dormitory-menu-inline.micro-dormitory-menu-root .micro-dormitory-menu-item {
  .micro-dormitory-checkbox-wrapper {
    width: 100%;
  }
}
// 滚动条
&::-webkit-scrollbar {
  width: 6px;
}

&::-webkit-scrollbar-thumb {
  background: rgba(20, 20, 20, 0.2);
  border-radius: 3px;
}

&::-webkit-scrollbar-track {
  background: transparent;
}

// .micro-dormitory-checkbox input[type='checkbox'] {
//   cursor: pointer;
//   position: relative;
//   width: 1rem;
//   height: 1rem;
//   font-size: 0.9rem;
//   visibility: hidden;
// }
// .micro-dormitory-checkbox input[type='checkbox']::after {
//   position: absolute;
//   top: 0;
//   background-color: #33d883;
//   color: #fff;
//   width: 1rem;
//   height: 1rem;
//   display: inline-block;
//   visibility: visible;
//   padding-left: 0px;
//   text-align: center;
//   content: ' ';
//   border-radius: 50%;
// }

// .micro-dormitory-checkbox input[type='checkbox']:checked::after {
//   content: '✓';
//   font-size: 0.9rem;
//   font-weight: bold;
// }
// 显示圆圈
// /deep/.micro-dormitory-checkbox-inner {
//   border-radius: 10px !important;
// }
// /deep/.micro-dormitory-checkbox-checked .micro-dormitory-checkbox-inner {
//   border-radius: 10px !important;
// }
// /deep/.micro-dormitory-checkbox-checked::after {
//   border-radius: 10px;
// }
</style>
